<?php

/**
 * This is the model class for table "users".
 *
 * The followings are the available columns in table 'users':
 * @property integer $id
 * @property string $login
 * @property string $password
 * @property string $firstname
 * @property string $lastname
 * @property string $email
 * @property integer $is_admin
 * @property integer $status
 * @property string $last_login_on
 * @property string $language
 * @property integer $auth_source_id
 * @property string $created_on
 * @property string $updated_on
 * @property string $type
 * @property string $identity_url
 * @property string $email_notification
 * @property string $salt
 */
class User extends CActiveRecord
{
    public $password_repeat;
    public $verifyCode;
    public $rememberMe;

    private $_identity;
    
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'users';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('is_admin, status, auth_source_id', 'numerical', 'integerOnly'=>true),
            array('login, firstname, lastname', 'length', 'max'=>30),
            array('password', 'length', 'min'=>4, 'max'=>40),
            array('email', 'length', 'max'=>60),
            array('language', 'length', 'max'=>5),
            array('type, identity_url, email_notification', 'length', 'max'=>255),
            array('salt', 'length', 'max'=>64),
            array('email', 'email'),
            array('email', 'required', 'on'=>'lost_password'),
            array('email', 'exist', 'on'=>'lost_password'),
            array('login, email', 'unique', 'className'=>'User','on'=>'register'),
            array('login, firstname, lastname, email', 'required','on'=>'register'),
            array('password, password_repeat', 'required','on'=>'register'),
            array('password_repeat', 'compare', 'compareAttribute'=>'password', 'on'=>'register', 'message'=>Yii::t('account','Password must be repeated exactly.')),
            array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
            array('last_login_on, created_on, updated_on, password_repeat, verifyCode, rememberMe', 'safe'),
            array('created_on','default','value'=>new CDbExpression('CURRENT_TIMESTAMP()'),'on'=>'insert'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('login, firstname, lastname, email, is_admin, status, last_login_on, language, auth_source_id, created_on, updated_on, type, identity_url, email_notification, salt', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => Yii::t('account','ID'),
            'login' => Yii::t('account','Login'),
            'password' => Yii::t('account','Password'),
            'password_repeat' => Yii::t('account','Confirmation'),
            'verifyCode' => Yii::t('account','Verification code'),
            'firstname' => Yii::t('account','First name'),
            'lastname' => Yii::t('account','Last name'),
            'email' => Yii::t('account','Email'),
            'is_admin' => Yii::t('account','Administrator'),
            'status' => Yii::t('account','Status'),
            'last_login_on' => Yii::t('account','Last Login On'),
            'language' => Yii::t('account','Language'),
            'auth_source_id' => Yii::t('account','Auth Source'),
            'created_on' => Yii::t('account','Created On'),
            'updated_on' => Yii::t('account','Updated On'),
            'type' => Yii::t('account','Type'),
            'identity_url' => Yii::t('account','OpenID URL'),
            'email_notification' => Yii::t('account','email Notification'),
            'salt' => Yii::t('account','Salt'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('login',$this->login,true);
        $criteria->compare('firstname',$this->firstname,true);
        $criteria->compare('lastname',$this->lastname,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('is_admin',$this->is_admin);
        $criteria->compare('status',$this->status);
        $criteria->compare('last_login_on',$this->last_login_on,true);
        $criteria->compare('language',$this->language,true);
        $criteria->compare('auth_source_id',$this->auth_source_id);
        $criteria->compare('created_on',$this->created_on,true);
        $criteria->compare('updated_on',$this->updated_on,true);
        $criteria->compare('type',$this->type,true);
        $criteria->compare('identity_url',$this->identity_url,true);
        $criteria->compare('email_notification',$this->email_notification,true);
        $criteria->compare('salt',$this->salt,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
    
    /**
     * Returns the language name in current site language from language code.
     * @param string $languageCode standard language code.
     * @return languageName language name in current site language
     */
    private function getLanguageName($languageCode)
    {
        $languageName = Yii::app()->locale->getLanguage($languageCode);
        // i18n in Yii framework uses long and short language code (fr and fr_ca)
        // If the language name is NULL, the language code may longer than the one used by Yii
        // Let's try with only the two first characters
        if ($languageName == NULL)
            $languageName = Yii::app()->locale->getLanguage(substr($languageCode,0,2));
        return ucfirst($languageName);
    }
    
    /**
     * Returns the language list supported by the site.
     * @return languageList list of supported languages
     */
    public function getLanguageList()
    {
        // First element of the list is the default site language (source language)
        $languageList[Yii::app()->sourceLanguage] = $this->getLanguageName(Yii::app()->sourceLanguage);
        // Others languages have to be defined in messages folder (directory of site translations)
        $directoryIterator = new DirectoryIterator(Yii::app()->messages->basePath);
        foreach($directoryIterator as $directory)
            // .svn folder must be ignored in development environment
            if($directory->isDir() && !$directory->isDot() && $directory->getFilename()!==".svn")
                $languageList[$directory->getFilename()] = $this->getLanguageName($directory->getFilename());
        return $languageList;
    }
    
    /**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new UserIdentity($this->login,$this->password);
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
			Yii::app()->user->login($this->_identity,$duration);
			return true;
		}
		else
			return false;
	}

}